package com.yfux._05_tlias.controller;

import com.yfux._05_tlias.pojo.Dept;
import com.yfux._05_tlias.pojo.Result;
import com.yfux._05_tlias.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    DeptService deptService;

    @GetMapping
    public Result list() {
        log.info("查询所有部门数据.");
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        log.info("删除Id为{}的数据", id);
        int rows = deptService.deleteById(id);
        Result result = rows > 0 ? Result.success() : Result.error("删除Id为" + id + "的数据失败");
        return result;
    }

    @PostMapping
    public Result insert(@RequestBody Dept dept) {
        log.info("添加数据: {}", dept);
        int row = deptService.insert(dept);
        Result result = row > 0 ? Result.success() : Result.error("添加" + dept + "失败");
        return result;
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        log.info("查询Id为{}的部门.", id);
        Dept dept = deptService.findById(id);
        return Result.success(dept);
    }

    @PutMapping
    public Result update(@RequestBody Dept dept) {
        log.info("修改数据, 修改后: {}", dept);
        int row = deptService.update(dept);
        Result result = row > 0 ? Result.success() : Result.error("修改Id为" + dept.getId() + "的数据失败");
        return result;
    }
}
